package com.czl.module_storehouse.activity.borrow.add;

import android.os.Bundle;
import android.text.TextUtils;
import android.view.LayoutInflater;
import android.view.ViewGroup;
import android.widget.Button;
import android.widget.TextView;

import com.chad.library.adapter.base.BaseQuickAdapter;
import com.czl.base.data.bean.tengyun.ProductBean;
import com.czl.base.data.bean.tengyun.SortBean;
import com.czl.module_base.bean.ListBean;
import com.czl.module_base.http.HttpResponse;
import com.czl.module_base.mvp.presenter.InjectPresenter;
import com.czl.module_base.mvp.view.SimpleView;
import com.czl.module_service.event.BorrowAddEvent;
import com.czl.module_service.event.StorehouseHomeScanBackEvent;
import com.czl.module_storehouse.activity.base.BaseOperationActivity;
import com.czl.module_storehouse.adapter.BorrowAddAdapter;
import com.czl.module_storehouse.bean.BorrowInfoBean;
import com.czl.module_storehouse.bean.WorkGroupBean;
import com.czl.module_storehouse.bean.WorkerBean;
import com.czl.module_storehouse.databinding.ActivityBaseOperationBinding;
import com.czl.module_storehouse.databinding.HeaderBorrowAddBinding;
import com.czl.module_storehouse.listener.OnItemChangeListener;
import com.czl.module_storehouse.mvp.presenter.BorrowPresenter;
import com.czl.module_storehouse.mvp.presenter.CompanyPresenter;
import com.czl.module_storehouse.mvp.presenter.ProductPresenter;
import com.czl.module_storehouse.mvp.view.BorrowView;
import com.czl.module_base.widget.timeselector.TimeSelector;
import com.jeremyliao.liveeventbus.LiveEventBus;

import java.util.ArrayList;
import java.util.Date;
import java.util.List;

/**
 * @author xubin
 */
public class BorrowAddActivity extends BaseOperationActivity<ActivityBaseOperationBinding> implements
        OnItemChangeListener, BorrowView, SimpleView {

    private final BorrowInfoBean mBorrowInfoBean = new BorrowInfoBean();
    private BorrowAddAdapter mAdapter;
    private HeaderBorrowAddBinding mHeaderBinding;

    @InjectPresenter
    BorrowPresenter mBorrowPresenter;
    @InjectPresenter
    CompanyPresenter mCompanyPresenter;
    @InjectPresenter
    ProductPresenter mProductPresenter;

    @Override
    public ProductPresenter getProductPresenter() {
        return mProductPresenter;
    }

    @Override
    protected ActivityBaseOperationBinding getBinding(LayoutInflater layoutInflater) {
        return ActivityBaseOperationBinding.inflate(layoutInflater);
    }

    @Override
    protected void initData(Bundle savedInstanceState) {
        super.initData(savedInstanceState);
        mToolBinding.toolbarContentTitle.setText("借用单");
        mCommonSelectedOrScanBinding.textScan.setText("扫码借用物品");
        mCommonSelectedOrScanBinding.textSelected.setText("选择借用物品");
        mCommonSelectedOrganizationBinding.stvOrganization.setLeftString("借用部门");
        mCommonSelectedOrganizationBinding.stvPersonnel.setLeftString("借用人");
        mCommonSelectedOrganizationBinding.stvPersonnel.setRightString("选择借用人");
        binding.btnSure.setText("借用出库");
        binding.recyclerView.setAdapter(getAdapter());
    }

    @Override
    protected BaseQuickAdapter<SortBean, ?> getAdapter() {
        if (mAdapter == null) {
            mAdapter = new BorrowAddAdapter(new ArrayList<>(), this);
            mAdapter.setOnItemChildClickListener((adapter, view, position) -> startActivity(position));
            mHeaderBinding = HeaderBorrowAddBinding.inflate(getLayoutInflater());
            mHeaderBinding.tvReturnDate.setOnClickListener(v -> showTimeSelector(mHeaderBinding.tvReturnDate));
            mAdapter.addHeaderView(mHeaderBinding.getRoot());
            addFooterView(mAdapter);
        }
        return mAdapter;
    }

    @Override
    protected Button getButton() {
        return binding.btnSure;
    }

    @Override
    protected ViewGroup selectedOrganizationView() {
        return mHeaderBinding.flContent;
    }

    @Override
    protected ViewGroup selectedScanContainerView() {
        return mHeaderBinding.flAdd;
    }

    @Override
    protected void selectOrganization() {
        super.selectOrganization();
        mCompanyPresenter.selectOrganization();
    }

    @Override
    protected void selectUsersByCompanyId() {
        super.selectUsersByCompanyId();
        mCompanyPresenter.selectUsersByCompanyId(mOrganizationId);
    }

    @Override
    protected String getOperationTitle() {
        return "借用";
    }

    @Override
    protected int getMaxNum(SortBean sortBean) {
        return Integer.MAX_VALUE;
    }

    @Override
    protected void submit() {
        if (TextUtils.isEmpty(mOrganizationId)) {
            if (mWorkerBean == null) {
                showToast("请选择借用部门");
                return;
            }
        }
        if (mWorkerBean == null) {
            showToast("请选择借用人");
            return;
        }
        mBorrowInfoBean.setBorrowOrganizationId(Integer.parseInt(mOrganizationId));
        mBorrowInfoBean.setBorrowPersonId(mWorkerBean.getUserId());
        mBorrowInfoBean.setBorrowPersonName(mWorkerBean.getTname());
        String date = mHeaderBinding.tvReturnDate.getText().toString();
        if (TextUtils.isEmpty(date)) {
            showToast("请选择时间");
            return;
        }
        mBorrowInfoBean.setMoReturnDate(date);
        List<SortBean> list = new ArrayList<>();
        List<ProductBean> productList = new ArrayList<>();
        for (SortBean sortBean : mAdapter.getData()) {
            if (sortBean.getProductBean() == null) {
                list.add(sortBean);
            } else {
                productList.add(sortBean.getProductBean());
            }
        }
        mBorrowInfoBean.setSortList(list);
        mBorrowInfoBean.setProductList(productList);
        String remark = mFooterBinding.etRemark.getText().toString();
        mBorrowInfoBean.setBorrowComment(remark);
        String desc = mHeaderBinding.etDeptDesc.getText().toString();
        mBorrowInfoBean.setApplyComment(desc);
        if (mBorrowPresenter != null) {
            mBorrowPresenter.addBorrowInfo(mBorrowInfoBean);
        }
    }

    private void showTimeSelector(TextView textView) {
        TimeSelector timeSelector = new TimeSelector(this, time ->
        {
            textView.setText(time);
            mBorrowInfoBean.setMoReturnDate(time);
        }, "1990-01-01", "2099-12-31", TimeSelector.FORMAT_STR2, new Date());
        timeSelector.setScrollUnit(TimeSelector.SCROLLTYPE.YEAR,
                TimeSelector.SCROLLTYPE.MONTH,
                TimeSelector.SCROLLTYPE.DAY);
        timeSelector.show();
    }

    @Override
    public void onChange(int position) {
        setReceiveOrBorrowEnable();
    }

    @Override
    public void add(int position) {
        setReceiveOrBorrowEnable();
    }

    @Override
    public void remove(int position) {
        setReceiveOrBorrowEnable();
    }

    @Override
    public <T> void showHttpResponse(HttpResponse<T> httpResponse) {
        super.showHttpResponse(httpResponse);
        if (CompanyPresenter.TAG_COMPANY_GROUP.equals(httpResponse.getRequestTag())) {
            addChildWorkGroup(((ListBean<WorkGroupBean>) httpResponse.getData()).getList());
            showPopupWindowGroup();
        } else if (CompanyPresenter.TAG_COMPANY_USER_LIST.equals(httpResponse.getRequestTag())) {
            mWorkerBeanList = ((ListBean<WorkerBean>) httpResponse.getData()).getList();
            showPopupWindowUsers();
        } else if (BorrowPresenter.TAG_BORROW_ADD_INFO.equals(httpResponse.getRequestTag())) {
            if (homeScan) {
                LiveEventBus.get(StorehouseHomeScanBackEvent.class).post(new StorehouseHomeScanBackEvent());
            } else {
                LiveEventBus.get(BorrowAddEvent.class).post(new BorrowAddEvent(true, null));
            }
            showToast("借用成功");
            setResult(RESULT_OK);
            finish();
        }
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        if (mHeaderBinding != null) {
            mHeaderBinding.unbind();
        }
    }

}
